<?php
apf_require_controller('Oa_Attendance_Abstract');
apf_require_class('Tools_Uploader');
apf_require_class('Bll_Attendance_Role');
apf_require_class('Bll_Attendance_LeaveRecord');

class Oa_Attendance_AskLeaveController extends Oa_Attendance_AbstractController {

    public function handle_request() {
        $params = $this->request->get_parameters();
        $user_id = $_SESSION['user_id'];
        //年假信息
        $this->get_myannual();
        $bll_role = new Bll_Attendance_Role();
        $audit_user_ids = $bll_role->get_sup_id($user_id,array(1,2));
        $audit_users =  $bll_role->get_sup_name($audit_user_ids);

        foreach ($audit_users as $key => $list){
            if ($list == '梁伟平' && count($audit_users)==1) {
                $audit_users[$key] = $list;
            }elseif ($list == '梁伟平' && count($audit_users)==2)
            {
                unset($audit_users[$key]);
            }else {
                $audit_users[$key] = $list;
            }
        }
        //$bll = new Bll_Attendance_LeaveRecord();
        //$is_ever = $bll->is_check_same_leave('2013-01-06 14:00','2013-01-08 18:00','婚假',4555);
        //var_dump($is_ever);
        $data = array();
        if($this->is_post_request()){
            $data = array();
            if($params['cal'] == 'long'){
                $start = $params['start'];
                $end   = $params['end'];
                //如果为年假，判断是否还有可用年假
                if($params['type'] == '年假') {
                    $day = $this->calculate_leave_days($start, $end);
                }elseif($params['type'] == '婚假') {
                    $day = Tools_Tools::get_instance()->get_nature_many_day($start, $end);
                } elseif($params['type'] == '产前假') {
                    $day = Tools_Tools::get_instance()->get_nature_all_many_day($start, $end);
                } elseif($params['type'] == '产假') {
                    $day = Tools_Tools::get_instance()->get_baby_many_day($start, $end);
                } elseif($params['type'] == '公出') {
                    $start_last = intval(substr($start,11,2));
                    $end_last = intval(substr($end,11,2));
                    $day = $end_last - $start_last;
                } else {
                    $day = $this->calculate_leave_days($start, $end);
                }
                //判断时间是否冲突
                //后台查询数据判断
                //需要做时间处理
                $bll = new Bll_Attendance_LeaveRecord();
                //$is_ever = $bll->is_ever_apply($start,$end,$params['type'],$user_id);
                $is_ever_days = $bll->is_check_same_leave($start,$end,$params['type'],$user_id);
                $is_ever =0;
                $has_days ='';
                if(!empty($is_ever_days)){
                    $is_ever=1;
                    $has_days = implode('#', $is_ever_days);
                }
                echo json_encode(array('day'=>$day,'is_ever'=>$is_ever,'has_days'=>$has_days));
                exit;
            }else if($params['cal'] == 'annual'){
                $day = $this->calculate_annual_days($user_id);
                echo $day;
                exit;
            }else if($params['cal'] == 'overdue'){
                $marriage = $params['marriage'];
                $bool = $this->calculate_overdue($marriage);
                exit($bool);
            }elseif ($params['cal'] == 'chanjia') {
                $date = $this->get_antenatal($this->uinfo['user_id']);
                echo $date;
                exit;
            }else{
                /*$upDir = 'upload/attendance';
                $is_up = false;
                if($_FILES['file']['tmp_name']) {
                    $is_up = true;
                    $uploader = new Tools_Uploader('file');
                    $uploader->setValidExt(array(
                            '.jpg',
                            '.gif'
                    ));
                    $uploader->setUpDir(CODE_PATH . $upDir); // 需修改为你自己的路径
                }*/
                $up_img= '';
                if(!empty($params['img_file'])){
                    if(strpos($params['img_file'],"attendance")){
                        $up_img = str_replace("/upload/attendance/","",$params['img_file']);
                    }
                }
                apf_require_class('Bll_Attendance_Apply');
                $bll_apply = new Bll_Attendance_Apply();
                $now = time();
                $data = array(
                'user_id' => $user_id,
                'apply_time' => date("Y-m-d H:i:s", $now),
                'apply_time_ext' => $now,
                'start_time' => $params['start_time'],
                'end_time' => $params['end_time'],
                'leave_time' => $params['days'],
                'type' => $params['type'],
                'leave_reason' => $params['type'],
                'leave_desc' => $params['desc'],
                'leave_agent' => $params['agent'],
                'status' => '未审核',
                'r_user_id' => $audit_user_ids[1],
                'last_touch' => date("Y-m-d H:i:s"),
                'leave_agent' =>$params['agent'],
                'img'=>$up_img
                );

                if($params['type'] == '丧假'){
                    $data['leave_reason'] = $params['relation'];
                }
                if($params['type'] == '婚假'){
                    $leave_long = Tools_Tools::get_instance()->get_nature_many_day($params['start_time'], $params['end_time']);
                    if($leave_long > 10) {
                        $error[] = '婚嫁最多能请10天';
                    } elseif(!$this->calculate_overdue($params['delivery_time'])) {
                        $error[] = '领证日期已经超过6个月，不可使用婚假';
                    }
                }
                if($params['type'] == '年假'){
                    $day = $this->calculate_annual_days($user_id);
                    if($params['days'] > $day) {
                        $error[] = '您的年假不够！';
                    }
                }
                if($params['type'] == '产检'){
                    $is_can = $this->get_whether_have_ask_leave($user_id,$params['start_time'],$params['end_time']);
                    if(!$is_can) {
                        $error[] = '您当月已请过一次产检假！';
                    }
                }
                if($params['type'] == '产假'){
                    $start = date('Y-m-d');
                    $end = $params['delivery_time'];
                    $pre_day = Tools_Tools::get_instance()->get_nature_many_day($start, $end);
                    if($pre_day > 15 ) {//TODO || strtotime($start) > strtotime($end)有可能是提前生，所以不能判断时间
                        $error[] = '产假必须在预产期前15天内请';
                    }
                    $days = Tools_Tools::get_instance()->get_baby_many_day($params['start_time'], $params['end_time']);
                    if($days > 158) {
                        $error[] = '产假最多只能请98天+30天（晚育）';
                    }
                }
                if( in_array($params['type'],array('婚假','产前假','产假')) ){
                    if($params['type'] == '产前假' && $params['days'] > 75) {
                        $error[] = '产前假不能超过两个半月';
                    }
                    $start = date('Y-m-d');
                    $end = $params['delivery_time'];
                    $pre_day = Tools_Tools::get_instance()->get_nature_many_day($start, $end);
                    if($pre_day > 84) {
                        $error[] = '产前假必须在妊娠28周后请';
                    }
                    $data['delivery_time'] = $params['delivery_time'];
                }
                if($params['days'] > 3 && $params['type'] != '公出'){//公出在数据库中存的小时可能会大于3
                    if($audit_user_ids[2]!=6932){//当二级审批人为mike不记id
                        $data['b_user_id'] = $audit_user_ids[2];
                    }
                }
                /*if($is_up) {
                    if($uploader->upload()) {
                        $data['img'] = $uploader->getFileName();
                    } else {
                        $error[] = $uploader->getErrorMsg();
                    }
                }*/
                //检验数据，没有错误时允许提交
                if(count($error) > 0) {
                    echo "<script type='text/javascript'>";
                    foreach ($error as $key => $val) {
                        echo "alert('{$val}');";
                    }
                    echo "</script>";
                } else {
                    $bll_apply->apply($data);
                    if($params['type'] == '病假' && empty($data['img'])){
                        $tips = ",请一周内上传区级以上病假证明";
                    }
                    echo "<script type='text/javascript'>alert('申请成功{$tips}');document.location='".Tools_OAUrls::get_instance()->build_myapply_url()."'</script>";
                    $this->response->redirect('/myapply/',false,false);
                }

            }
        }
        $fd = isset($params['fd']) ? $params['fd'] : '';
        $fd_s = isset($params['s']) ? $params['s'] : '';
        $fd_e = isset($params['e']) ? $params['e'] : '';
        $fd_st = $fd_et = '';
        if($fd){
            $fd_st = $params['fd'].' '.$fd_s;
            $fd_et = $params['fd'].' '.$fd_e;
        }
        $fd_days = 0;
        if($fd_s == '09:00' && $fd_e == '18:00'){
            $fd_days = 1;
        }elseif(($fd_s == '09:00' && $fd_e == '14:00') || ($fd_s == '14:00' && $fd_e == '18:00')){
            $fd_days = 0.5;
        }
        $this->request->set_attribute('fd_st',$fd_st);
        $this->request->set_attribute('fd_et',$fd_et);
        $this->request->set_attribute('fd_days',$fd_days);
        $this->request->set_attribute('audit_users',$audit_users);
        return 'Oa_Attendance_AskLeave';
    }

    private function get_myannual(){
        apf_require_class('Bll_Attendance_ApplyType');
        $t_bll = new Bll_Attendance_ApplyType();
        $type = $t_bll->get_all_leave_type();
        $this->request->set_attribute('annual',$this->get_all_annual());
    }

    public function get_all_annual(){
        $result = array();
        //$this->uinfo['user_id'] = 113;
        //$this->uinfo['enter_date'] = '2010-01-05';
        //如果用户未登录，返回空数组
        if(empty($this->uinfo['user_id'])) {
            return $result;
        }
        apf_require_class('Tools_Tools');
        apf_require_class('Bll_Attendance_UserExt');
        $bll = new Bll_Attendance_UserExt();
        $l_bll = new Bll_Attendance_LeaveRecord();
        $annual['all'] = Tools_Tools::get_instance()->annual($this->uinfo['enter_date']);
        $annual['used'] = $bll->get_used_annual($this->uinfo['user_id']);
        $annual['left'] = $annual['all'] - $annual['used'];
        $start = date('Y-m-d',mktime(0,0,0,1,0,date('Y')));
        $end = date('Y-m-d',mktime(0,0,0,1,0,date('Y')+1));
        //用户当年请假总数
        $clear_day = $l_bll->get_annual_by_condition($this->uinfo['user_id'],$start,$end);
        //推算需要清零的假
        $sys = Tools_Tools::get_instance()->clear_annual_to_zero($this->uinfo['enter_date'],$start);
        $annual['need_do'] = 0;
        if($sys['left_annual'] >= $clear_day) {
            $annual['need_do'] = $sys['left_annual'] - $clear_day;
        }
        $annual['clear_date'] = date('Y.m.d',mktime(0,0,0,1,0,date('Y')+1));
        return $annual;
    }

    private function calculate_leave_days($start,$end){
        apf_require_class("Tools_Tools");
        $tools = Tools_Tools::get_instance();
        $day = $tools->get_many_day($start,$end);
        return $day;
    }
    /**
     * 产检检查当月是否已申请
     * @param int $user_id
     * @param string $start
     * @param string $end
     * **/
    private function get_whether_have_ask_leave($user_id,$start,$end) {
        $result = false;
        if(empty($user_id)) {
            return $result;
        }
        $bll = new Bll_Attendance_LeaveRecord();
        $where['user_id'] = $user_id;
        $where['type'] = '产检';
        $alldate = $bll->get_leave_record_data($where);
        if(empty($alldate)) {
            return true;
        }
        foreach ($alldate as $key => $val) {
            $h_start = strtotime($val['start_time']);
            //产检一个月只能请一次
            if($val['status'] != '已批准' && $val['status'] != '未审核') {
                continue;
            }
            if(date('Ym',$h_start) == date('Ym',strtotime($start)) || date('Ym',$h_start) == date('Ym',strtotime($end))) {
                return false;
            }
        }
        return true;
    }

    private function calculate_annual_days($user_id){
        apf_require_class("Tools_Tools");
        $tools = Tools_Tools::get_instance();
        $enterdate = $_SESSION['enter_date'];
        $day = $tools->annual($enterdate);
        if($day <=0){
            return 0;
        }else{
            apf_require_class("Bll_Attendance_UserExt");
            $bll_ext = new Bll_Attendance_UserExt;
            $used_day = $bll_ext->get_used_annual($user_id);
        }
        return max(($day-$used_day),0);
    }

    private function calculate_overdue($marriage){
        $six_month_ago = date("Ymd",strtotime("now -6 month"));
        $marriage_day  = date("Ymd",strtotime($marriage));
        return $marriage_day >= $six_month_ago;
    }

    //通过 user_id 获取产前假
    public function get_antenatal($user_id)
    {
        $bll = new Bll_Attendance_LeaveRecord();
        $where = array('user_id'=>$user_id,'type'=>'产前假','status'=>'已批准');
        $result = $bll->get_leave_record_data($where,1);
        return $result[0]['delivery_time'];
    }

}
